<template>
    <div class="login">
        <div class="login-left">
            <div class="login-left-top">
                <img class="logo" src="../../assets/image/logo.png" alt="">
            </div>
        </div>
        <div class="login-right">
            <div class="right-top-img" />
            <div>
                <div class="login-text">青岛盛益兴信息技术有限公司</div>
                <div class="login-form">
                    <div class="login-title">大象物流管理后台</div>
                    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" class="demo-ruleForm">
                        <!-- <el-form-item prop="business">
              <el-input v-model="ruleForm.business" placeholder="请输入企业代码" />
            </el-form-item> -->
                        <el-form-item prop="username">
                            <el-input v-model="ruleForm.username" type="text" auto-complete="off" clearable
                                autocomplete="off" @mousedown.native="nameMouse" :readonly="namebool"
                                placeholder="请输入登录账号" />
                        </el-form-item>
                        <el-form-item prop="password">
                            <el-input v-model="ruleForm.password" type="password" placeholder="请输入登录密码"
                                auto-complete="off" clearable autocomplete="off" @mousedown.native="nameMouse"
                                :readonly="namebool" show-password @input.native="onInput($event, ruleForm.password)" />
                        </el-form-item>
                        <el-form-item prop="code">
                            <div class="code">
                                <div>
                                    <el-input v-model="ruleForm.code" placeholder="请输入验证码" />
                                </div>
                                <div v-if="codeShow == true" class="code-img"
                                    style="width: 32%;border: 1px solid #eee;border-radius: 6px;" @click="updataCode">
                                    <img v-if="base64Image" :src="base64Image" alt=""
                                        style="width: 100%; height: 36px; border-radius: 6px; border: 1px solid rgb(229, 230, 235);">
                                </div>
                            </div>
                        </el-form-item>
                        <el-form-item style="text-align: left;">
                            <el-checkbox v-model="rememberMe" style="margin-bottom: 10px;">记住密码</el-checkbox>
                        </el-form-item>
                        <el-form-item>
                            <!-- @click.native.prevent="handleLogin"  :loading="loading" -->
                            <el-button type="primary" style="width:100%;" @click="submitForm('ruleForm')"
                                v-if="ishandle">登录</el-button>
                            <el-button type="primary" style="width:100%;" disabled icon="el-icon-loading"
                                v-else>正在登录</el-button>
                        </el-form-item>
                        <!-- <el-form-item>
                            <p><span>企业账号注册</span> <span /> <span>忘记密码</span></p>
                        </el-form-item> -->
                    </el-form>
                </div>
            </div>
            <div class="right-bottom-img" />
        </div>
    </div>
</template>

<script>
// import { validUsername } from '@/utils/validate'
// import SocialSign from './components/SocialSignin'
import { codeImg, goLogin, getMenusList } from '@/api/api'
import CryptoJS from 'crypto-js';
export default {
    name: 'Login',
    //   components: { SocialSign },
    data () {

        var checkCode = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('验证码不能为空'));
            } else if (!/^\d{4}$/.test(value)) {  // {{ edit_2 }} 添加四位数字校验
                callback(new Error('请输入有效验证码'));
            } else {
                callback();
            }
        };
        var validateUser = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入账号'));
            } else {
                callback();
            }
        };
        var validatePass = (rule, value, callback) => {
            console.log('我是value', value.length);
            if (value === '') {
                callback(new Error('请输入密码'));
            } else if (value.length < 6) {  // {{ edit_1 }}
                console.log('我是value', value.length);
                callback(new Error("密码最少为6位"));
            } else {
                callback();
            }
        };
        return {
            MenusList: [],
            rememberMe: false,
            base64Image: '',
            imgKey: '',
            codeShow: true,
            ruleForm: {
                // business: '1001',
                username: '',
                password: '',
                code: ''
            },
            namebool: true,
            updataCodes: null,
            rules: {
                // business: [
                //   { validator: validateBus, trigger: 'blur' }
                // ],
                username: [
                    { validator: validateUser, trigger: 'blur' }
                ],
                password: [
                    { validator: validatePass, trigger: 'blur' }
                ],
                code: [
                    { validator: checkCode, trigger: 'blur' }
                ]
            },
            ishandle: true
        }
    },
    watch: {
        $route: {
            handler: function (route) {
                const query = route.query
                if (query) {
                    this.redirect = query.redirect
                    // this.otherQuery = this.getOtherQuery(query)
                }
            },
            immediate: true
        }
    },

    created () {
        // this.getCode()
    },
    mounted () {
        // this.getMenu()
        this.getCode()
        this.updataCodes = setInterval(() => {
            this.getCode()
        }, 60000);
        // 在组件挂载时检查 localStorage 是否有保存的用户名和密码
        const savedUsername = localStorage.getItem('usernameb');
        const savedPassword = localStorage.getItem('passwordb');
        const remember = localStorage.getItem('rememberb');
        if (savedUsername) {
            this.ruleForm.username = savedUsername;
        }
        if (savedPassword) {
            this.ruleForm.password = savedPassword;
        }
        if (remember) {
            this.rememberMe = Boolean(remember);
        }
    },
    methods: {
        submitForm (formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.ishandle = false
                    if (this.rememberMe) {
                        // 如果选择了“记住密码”，将用户名和密码存储在 localStorage
                        localStorage.setItem('usernameb', this.ruleForm.username);
                        localStorage.setItem('passwordb', this.ruleForm.password);
                        localStorage.setItem('rememberb', this.rememberMe);
                    } else {
                        // 否则，清除 localStorage 中的用户名和密码
                        localStorage.removeItem('usernameb');
                        localStorage.removeItem('passwordb');
                        localStorage.removeItem('rememberb');
                    }
                    const formData = new FormData()
                    const encryptedPassword = CryptoJS.MD5(String(this.ruleForm.password)).toString();
                    formData.append('account', this.ruleForm.username) // 添加文件
                    formData.append('pwd', encryptedPassword) // 添加文件
                    formData.append('group_id', 1000) // 添加文件
                    formData.append('captcha', this.ruleForm.code) // 添加文件
                    formData.append('captcha_key', this.imgKey) // 添加文件

                    goLogin(formData).then(res => {
                        clearInterval(this.updataCodes);
                        console.log(res, '我是登录')
                        if (res.status === 200) {
                            localStorage.setItem('token', res.data.token)
                            localStorage.setItem('map_key', res.data.map_key.js_map_key)
                            localStorage.setItem('map_secret', res.data.map_key.js_map_secret_key)
                            localStorage.setItem('real_name', res.data.real_name)
                            this.$router.push('/index')
                            this.$message({
                                message: '登录成功',
                                type: 'success'
                            })
                            this.getMenu()
                            const token = res.data.token
                            // this.$store.commit('ADD_ROUTE')
                            this.$store.commit('SET_TOKEN', token)
                            this.$store.commit('SET_ISLOADROUTERS', true)
                            setTimeout(() => {
                                this.ishandle = true
                            }, 1000);
                        } else {
                            this.ruleForm.code = ''
                            this.getCode()
                            this.ishandle = true
                        }
                    }).catch(err => {
                        this.ishandle = true
                    })
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        // 用户权限菜单
        getMenu () {
            getMenusList().then(res => {
                console.log('我是菜单', res);
                if (res.status == 200) {
                    this.MenusList = res.data.list
                    // this.SET_MENUS_LIST(this.MenusList); // 将菜单列表存储到 Vuex
                    this.$store.dispatch('getlist', this.MenusList)
                    this.$store.commit('ADD_ROUTE')
                    // console.log('9999999999999999999999999');

                }
            })
        },
        resetForm (formName) {
            this.$refs[formName].resetFields()
        },
        // 获取图片验证码
        getCode () {
            codeImg().then(res => {
                console.log(res, '我是二维码图片')
                if (res.status === 200) {
                    this.base64Image = res.data.captcha.img
                    this.imgKey = res.data.captcha.key
                    console.log(this.base64Image, '>>>>>>>>>>>>>>')
                }
            })
        },
        // 更新验证码
        updataCode () {
            this.getCode()
        },
        // 阻止浏览器默认记忆
        nameMouse (e) {
            if (e.target.localName == 'i') {
                // console.log(this.pagerequest, '1111111111111');
                this.$set(this.pagerequest, 'empNm', '')
                // Vue.set(this.pagerequest, 'empNm', '');
                // const num = 111
                // num = 222
            }
            this.namebool = true;
            setTimeout(() => this.namebool = false, 0)
        },
        onInput (event, val) {
            if (val.length === 0) {
                // this.onBlur(event)
                // this.onFocus(event)
                this.namebool = true;
                setTimeout(() => this.namebool = false, 0)
            }
        },
        // // 登录
        // getLogin () {

        // },

        // 自带
        // checkCapslock(e) {
        //   const { key } = e
        //   this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
        // },
        // showPwd() {
        //   if (this.passwordType === 'password') {
        //     this.passwordType = ''
        //   } else {
        //     this.passwordType = 'password'
        //   }
        //   this.$nextTick(() => {
        //     this.$refs.password.focus()
        //   })
        // },
        // getOtherQuery(query) {
        //   return Object.keys(query).reduce((acc, cur) => {
        //     if (cur !== 'redirect') {
        //       acc[cur] = query[cur]
        //     }
        //     return acc
        //   }, {})
        // }
    }
}
</script>

<style lang="scss" scoped>
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

.login {
    display: flex;
    width: 100%;
    min-height: 100vh;
    background-color: rgb(247, 248, 250);
}

.login-left {
    background: url(../../assets/image/imageLogin.jpeg) no-repeat center center;
    // background-size: 100% auto;
    background-size: cover;
    // background-size: auto 100%;
    width: 50%;
    height: auto;
}

.login-left-top {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 62, 255, 0.35);
}

.logo {
    margin-top: 32px;
    margin-left: 32px;
}

.login-right {
    width: 50%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    position: relative;
    text-align: center;
    margin: 0 auto;
}

.right-top-img {
    width: 100%;
    height: 200px;
    background: url(../../assets/image/right-top.png) no-repeat;
    background-size: cover;
}

.right-bottom-img {
    width: 100%;
    height: 200px;
    background: url(../../assets/image/right-bottom.png) no-repeat;
    background-size: cover;
}

.login-title {
    position: absolute;
    top: -70px;
    left: 2px;
    font-family: PingFang SC;
    font-weight: 500;
    font-size: 26px;
    text-align: center;
    // width: 312px;
    width: 100%;
}

.login-text {
    position: absolute;
    bottom: 4%;
    // left: -6px;
    font-family: PingFang SC;
    font-weight: 400;
    font-size: 14px;
    text-align: center;
    // width: 312px;
    width: 100%;
}

.login-form {
    width: 368px;
    // height: 420px;
    // width: 45%;
    height: auto;
    // left: 10%;
    // right: 10%;
    // top: 10%;
    // bottom: 10%;
    // margin: 0 auto;
    background-color: #fff;
    border-radius: 10px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -45%);
    padding: 40px 24px 20px;
}

.el-form-item {
    margin-bottom: 20px;
}

::v-deep .el-form-item--medium .el-form-item__content {
    line-height: 0px;
}

.code {
    display: flex;
    width: 100%;
    justify-content: space-between;
}

.code-img {
    // width: 100px;
    // height: 36px;
}

.demo-ruleForm {
    // position: absolute;
}
</style>
